#pragma once
#include <ESPAsyncWebServer.h>
#include <ArduinoJson.h>
#include <AsyncJson.h>

namespace ganix
{
    namespace http_server
    {
        AsyncWebServer *server;

        void log_request_info(AsyncWebServerRequest *request) {
            Serial.printf("request handled:\n \tversion:%d\n \tmethod:%s\n \turl:%s\n \thost:%s\n",
             request->version(),
             request->methodToString(),
             request->url().c_str(),
             request->host().c_str());
        }

        void _on_not_found(AsyncWebServerRequest *request) {
            log_request_info(request);
            Serial.printf("404: %s\n", request->url().c_str());
            request->send(404, "text/plain", "404: Not Found");
        }

        AsyncWebServer *get_server() {
            return server;
        }

        void handle_hello(AsyncWebServerRequest *request) {
            log_request_info(request);
            request->send(200, "text/plain", "hello from ganix~");
        }

        void init(int port = 80) {
            server = new AsyncWebServer(port);
            server->onNotFound(_on_not_found);
            server->begin();
            server->on("/hello", handle_hello);
        }

        void on_json(const char* uri, ArJsonRequestHandlerFunction cb) {
            AsyncCallbackJsonWebHandler *handler  = new AsyncCallbackJsonWebHandler(uri, cb);
            server->addHandler(handler);
        }
    } // namespace http_server
    
} // namespace ganix
